<?php
/**
 * ooPHP - object oriented PHP framework
 * @author Kamil Mikolajczyk ( rego (at) gazeta (dot) pl )
 * @version 1.0
 *
 */

/**
 * Represents single html element and it's children and attributes
 * @author Kamil Mikolajczyk ( rego (at) gazeta (dot) pl )
 * @version 1.0
 */
 class Element
 {
 	/**
 	 * Name of the tag
 	 * @var string
 	 */
 	private $tagname;
 	
 	/**
 	 * Array of elements
 	 * @var Element[]
 	 */
 	private $children = array();
 	
 	/**
 	 * Array of attributes
 	 * @var string[]
 	 */
 	private $attributes = array();
	
	private $innerText = "";
 	
 	/**
 	 * Constructor, sets tagname and optionally id and class
 	 * @param $tagname tagname to be set
 	 * @param $id element's id
 	 * @param $class element's class
 	 */
 	function Element($tagname, $id = null, $class = null, $text = null)
 	{ 	
 		$this -> tagname = $tagname;
 		if($id != null)
 			$this -> addAttribute('id="'.$id.'"');
 		if($class != null)
 			$this -> addAttribute('class="'.$class.'"');
		if($text !=null)
			$this -> addText($text);
 	}
 	
 	/**
 	 * Adds new element to elements' array
 	 * @param $e an element to be added
 	 */
 	function addElement($e)
 	{
		if($this -> innerText != "")
			throw new Exception("Element::addElement() -> Element has inner text, can't add children");
 		$this -> children[] = $e;
 	}
 	
 	/**
 	 * Adds new element to attributes' array
 	 * @param $a an attribute to be added
 	 */
 	function addAttribute($a)
 	{
	
 		$this -> attributes[] = $a;
 	}
	
	/**
	 * Adds inner text
	 * @param $t text
	 */
	function addText($t)
	{
		if(isset($this -> children[0]))
			throw new Exception("Element::addText() -> Element has children, can't add inner text");
		$this -> innerText =  $t;
	}
 	
 	/**
 	 * Returns string containing tag's attributes separated with spaces
 	 * @return string
 	 */
 	function getAttributes()
 	{
 		$retVal = "";
 		foreach($this -> attributes as $a)
 			$retVal .= " ".$a;	
 		return $retVal;  
 	}
 	
 	/**
 	 * Renders whole element
 	 */
 	function render($indents = 0)
 	{
 		Printer::writeln("<".$this -> tagname.$this -> getAttributes().">$this->innerText", $indents);
 		foreach($this -> children as $element)
 		{
 			$element -> render(1 + $indents);
 		}
 		Printer::writeln("</".$this -> tagname.">", $indents);
 	}
 }
 ?>